package com.dayuanit.dy17.atm.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.dayuanit.dy17.atm.dto.ResponseDTO;
import com.dayuanit.dy17.atm.service.IRechargeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
public class RechargeController extends BaseController {

    @Autowired
    private IRechargeService rechargeService;

    @RequestMapping(value = "/card/rechage", method = RequestMethod.POST)
    public ResponseDTO recharge(long cardId, String amount, String password, HttpSession session) {
        return ResponseDTO.success(rechargeService.rechargeCard(cardId, amount, password, getUserId(session)));
    }

    @RequestMapping("/pay/alipayNotify")
    public ResponseDTO alipayNotify(HttpServletRequest request) {
        System.out.println("支付宝异步通知来了！");
        //订单支付成功了
        String out_trade_no = request.getParameter("out_trade_no");
        System.out.println("out_trade_no=" + out_trade_no);

        Map<String, String[]> requestParameterMap = request.getParameterMap();
        Map<String, String> paramsMap = new HashMap<>(requestParameterMap.size());
        for (Map.Entry<String, String[]> entry : requestParameterMap.entrySet()) {
            paramsMap.put(entry.getKey(), entry.getValue()[0]);
            System.out.println(entry.getKey() + "=" + entry.getValue()[0]);
        }

        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4SZgs0ZcIyvfS4hv2WEY PtoLpTCmza2IQKsLWxXHWwIFgPsnDB61jvNG9Oij7pmxx/+JMOWkcdVj1ltoRShH Dy3HAelIYxXnpKnHI3x9c6PyYUIX+szZ/dlkCEEbJPQ0tQqvkauK2ue3gDTBeWw/ frSbRUh0sQu47IUX8XO0MoUZDo62/5mnRnq4S+BKltL08eV7Cb5U+d/sIoce/IuR rDe9IKzdRk+efsSGK52nttuMa5NBOXpZrOg4MdLlhepc/g5xuZAIHkn+MAlW/gRD NfKvfOHh49ghpkO8ilNCQEC3KTn6uccl1DfxWcbgm0Slk5d/4XJ0dJWkarcsTcr2 nQIDAQAB", "utf-8", "RSA2"); //调用SDK验证签名
            if(signVerified){
                System.out.println("阿里支付异步通知验证签名成功");
                // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            }else{
                // TODO 验签失败则记录异常日志，并在response中返回failure.
                System.out.println("阿里支付异步通知验证签名失败。。");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResponseDTO.success();
    }
}
